<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Admin;
use App\Models\Project;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin', ['except' => ['login']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'username' => 'required|max:20',
            'password' => 'required'
        ], [
            'username.required' => '请输入登录名',
            'password.required' => '请输入密码',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $data = $validate->getData();

        $admin = Admin::where('username', $data['username'])->first();

        if (empty($admin) || !$token = JWTAuth::fromUser($admin)) {
            return showError('账号不存在');
        }
        if (!Hash::check($data['password'], $admin->password)) {
            return showError('用户密码错误');
        }
        if (0 == $admin->status) {
            return showError('用户已被禁用');
        }

        return $this->respondWithToken($token);

    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth('admin')->logout();

        return showSuccess('退出成功');
    }

    /**
     * Refresh a token.
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth('admin')->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        $data=[
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('admin')->factory()->getTTL() * 60
        ];
        return showData($data);
    }

        /**
         * Get the authenticated User.
         *
         * @return \Illuminate\Http\JsonResponse
         */
        public function adminInfo(Request $request)
        {
            $data=auth('admin')->user();
            $data['project_name']=Project::query()->where('id',$data['project_id'])->value('name');
              
            return showData($data);
        }
}

